#session.forget() # comment or remove if you want to store sessions

def index():
    if not session.token:
        redirect(URL(r=request,f=login))
    else:
        if len(request.vars):
            return walk()
        else:
            return dict(curpath='',files=['c:\\','d:\\'])
    
def walk():
    import os
    from gluon.contenttype import contenttype
    path=(request.vars.path).decode('utf-8').encode('gbk')
    name=(request.vars.file).decode('utf-8').encode('gbk')
    if name[-1]=='\\':
        for root,dirs,files in os.walk(os.path.join(path,name)):
            for i in range(len(files)):
                files[i]=files[i].decode('gbk').encode('utf-8')
            for i in range(len(dirs)):
                dirs[i]=dirs[i].decode('gbk').encode('utf-8')
                dirs[i]=dirs[i]+'\\'
            dirs.extend(files)
            return dict(files=dirs,curpath=os.path.join(path,name).decode('gbk').encode('utf-8'))
    else:
        try:
            s=open(os.path.join(path,name),'rb').read()
        except:
            return dict(curpath='',files='')
        else:
            response.headers['Content-Type']=contenttype(name)
            response.headers['Content-Disposition']=" filename=%s" %(name)
            return s
        
        
def login():
    form=FORM(TABLE(TR('User:',INPUT(_name='user',requires=IS_NOT_EMPTY())),
                    TR('Password:',INPUT(_name='password',_type='password',requires=IS_NOT_EMPTY())),
                    TR('',INPUT(_type='submit',_value='Login'))))
#    session.token=0
#    form=SQLFORM(db.user,fields=['name','password'])
    if form.accepts(request.vars,session):
        row=db((db.user.name==request.vars.user)&(db.user.password==request.vars.password)).select()
        if len(row)>0:
            session.token=1
            redirect(URL(r=request,f='index'))
#        else:
#            session.token=0
#            redirect(URL(r=request,f=login))
#    else:
#        redirect(URL(r=request,f=login))
    return dict(form=form)